package com.service.single.example.file;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.service.single.entity.SystemUser;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用hutool 实现 excel 导入导出
 */
@Slf4j
public class ExcelParse {

    /**
     * 读取指定行
     *
     * @param args
     */
    public static void main(String[] args) {
        ExcelReader reader = ExcelUtil.getReader("/Users/Downloads/测试.xlsx");
        List<List<Object>> mapList = reader.read(0, 0, false);
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (List<Object> objects : mapList) {
                System.out.println(objects.get(0).toString());
            }
        }
    }

    public void uploadExcel(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("Excel标题名称", "对应实体类别名");
            List<SystemUser> personList = reader.readAll(SystemUser.class);
            for (SystemUser systemUser : personList) {
                System.out.println(JSON.toJSONString(systemUser));
            }
            log.info("文件导入成功");
        } catch (Exception e) {
            log.error("文件导入失败 {}", e);

        }
    }

    /**
     * 导出 xls
     * 其他格式导出看hutool
     */
    @SneakyThrows
    public void downloadExcel() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        // 需要导出的数据集
        List<SystemUser> personList = new ArrayList<>();

        ExcelWriter writer = ExcelUtil.getWriter();
        writer.addHeaderAlias("实体类字段名", "对应Excel标题名称");
        writer.setOnlyAlias(true);
        writer.write(personList, true);
        // 设置字号
        Font font = writer.createFont();
        font.setFontHeightInPoints((short) 16);
        writer.getStyleSet().setFont(font, false);
        // 设置列宽
        writer.getSheet().setDefaultColumnWidth(24);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 注意这里如果需要设置中文文件名，需要重新编码
        String filename = new String("用户表_".getBytes(), "iso8859-1") + LocalDate.now().format(formatter) + ".xls";
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

}
